package com.example.github.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class TransActionJDBC {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://127.0.0.1:3306/lc-cc";
        String username = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, username, password);
        String sql1 = "update person set name = 'she' where id = 1";
        String sql2 = "update person set name = 'he' where id = 2";
        Statement statement = connection.createStatement();
        try{
            // ==================开启事务=================
            connection.setAutoCommit(false);
            int update1 = statement.executeUpdate(sql1);
            System.out.println(update1);
            // int i = 3/0; // 手动制造异常
            int update2 = statement.executeUpdate(sql2);
            System.out.println(update2);
            // ============提交事务==========
            // 程序运行到此处，说明没有出现任何问题，则需求提交事务
            connection.commit();
        }catch (Exception e){
            connection.rollback();
            e.printStackTrace();
        }
    }
}
